package com.mainbo.modular.system.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.mainbo.core.common.constant.Const;
import com.mainbo.core.shiro.SessionKey;
import com.mainbo.core.shiro.ShiroKit;
import com.mainbo.core.util.Result;
import com.mainbo.core.util.StringUtil;
import com.mainbo.modular.jms.MessageTypes;
import com.mainbo.modular.system.dao.PtAccountMapper;
import com.mainbo.modular.system.dao.PtOrgMapper;
import com.mainbo.modular.system.dao.PtRoleMapper;
import com.mainbo.modular.system.model.*;
import com.mainbo.modular.system.dao.PtUserRoleMapper;
import com.mainbo.modular.system.model.meta.MetaUtils;
import com.mainbo.modular.system.model.meta.vo.Meta;
import com.mainbo.modular.system.service.IPtAccountService;
import com.mainbo.modular.system.service.IPtRoleService;
import com.mainbo.modular.system.service.IPtUserRoleService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 切换工作空间 服务实现类
 * </p>
 *
 * @author moshang
 * @since 2020-02-22
 */
@Service
public class PtUserRoleServiceImpl extends ServiceImpl<PtUserRoleMapper, PtUserRole> implements IPtUserRoleService {

    @Resource
    private PtUserRoleMapper ptUserRoleMapper;
    @Resource
    private PtOrgMapper ptOrgMapper;
    @Resource
    private PtRoleMapper ptRoleMapper;
    @Resource
    private IPtRoleService ptRoleService;
    @Resource
    private IPtAccountService accountService;
    @Override
    public void addOrEditPostManage(String accountId, String spaceId, Model model) {
        if (StringUtils.isNotEmpty(spaceId)) {
            PtUserRole us = ptUserRoleMapper.selectById(spaceId);
            if (us != null && StringUtils.isNotEmpty(us.getOrgId()) && !Const.DEFAULT_ORG_ID.equals(us.getOrgId())) {
                PtOrg org = ptOrgMapper.selectById(us.getOrgId());
                if (org != null) {
                    List<Meta> phases = MetaUtils.getOrgTypeProvider().listAllPhase(org.getSchoolings());
                    model.addAttribute("metaList", phases);
                    if (us.getPhaseId() != null && us.getPhaseId() != 0) {
                        String areaIds = org.getAreaIds();
                        Integer[] areaId = StringUtil.toIntegerArray(areaIds.substring(1, areaIds.lastIndexOf(",")), ",");
                        List<Meta> grades = MetaUtils.getOrgTypeProvider().listAllGrade(org.getSchoolings(), us.getPhaseId());
                        List<Meta> subjects = MetaUtils.getPhaseSubjectProvider().listAllSubject(us.getOrgId(), us.getPhaseId(),
                                areaId);
                        model.addAttribute("grades", grades);
                        model.addAttribute("subjects", subjects);
                    }
                }
            }
            if (us != null && us.getRoleId() != null) {
                PtRole role = ptRoleMapper.selectById(us.getRoleId());
                model.addAttribute("role", role);
            }
            model.addAttribute("us", us);
        }
        PtAccount a = accountService.selectById(accountId);
        PtOrg org = ptOrgMapper.selectById(a.getOrgId());
        List<PtRole> roleList = null;
        roleList = ptRoleService.getRoleByScope(a.getOrgId(), PtRoleType.APPLICATION_SCHOOL);
        if (org != null) {
            List<Meta> phases = MetaUtils.getOrgTypeProvider().listAllPhase(org.getSchoolings());
            model.addAttribute("metaList", phases);
        }
        model.addAttribute("roleList", roleList);
        model.addAttribute("accountId", accountId);
        model.addAttribute("org", org);
    }

    @Override
    public Result saveAreaPostManage(PtUserRole us, Result result) {
        result.setCode(Result.SUCCESS);
      PtAccount currentUser= ShiroKit.getSessionAttr(SessionKey.CURRENT_USER);
        String accountId = us.getAccountId();
        EntityWrapper<PtUserRole> entityWrapper=new EntityWrapper<>();
        if (StringUtils.isNotEmpty(us.getId())) { // 职务是否存在
            entityWrapper.notIn("id",us.getId());
        }

        entityWrapper.eq("account_id",accountId);
        entityWrapper.eq("role_id",us.getRoleId());
        entityWrapper.eq("phase_id",us.getPhaseId());
        entityWrapper.eq("subject_id",us.getSubjectId());
        entityWrapper.eq("grade_id",us.getGradeId());
        List<PtUserRole> usList = selectList(entityWrapper);
        if (usList.size() > 0) {
            result.setCode(Result.FAIL);
            result.setMsg("该职务已经存在！");
            return result;
        }

        PtAccount account = accountService.findAccountWithInfo(accountId);
        if (account != null) {
            PtOrg org = ptOrgMapper.selectById(account.getOrgId());

            if (StringUtils.isEmpty(us.getId())) { // 新增用户职务
                us.setAccountId(accountId);
                if (org != null) {
                    us.setName(account.getUserInfo().getName());
                    us.setOrgId(org.getId());
                }
                us.setSysRoleId(account.getUserType());
                us.setEnable(true);
                if (us.getRoleId() != null) {
                    PtRole role = ptRoleMapper.selectById(us.getRoleId());
                    if (!role.getShowPhase()) {
                        us.setPhaseId(0);
                    }
                    if (!role.getShowGrade()) {
                        us.setGradeId(0);
                    }
                    if (!role.getShowSubject()) {
                        us.setSubjectId(0);
                    }
                }
                us.setCrtId(currentUser.getId());
                us.setLastupId(currentUser.getId());
                us.setCrtDttm(new Date());
                us.setLastupDttm(new Date());
                ptUserRoleMapper.insert(us);
                accountService.sendUserRoleMessege(MessageTypes.USER_ROLE_ADD.name(), us);
            } else { // 修改用户职务
                PtUserRole space = new PtUserRole();
                space.setId(us.getId());
                space.setAccountId(accountId);
                space.setRoleId(us.getRoleId());
                space.setName(null);
                if (org != null) {
                    space.setOrgId(org.getId());
                }
                if (us.getRoleId() != null) {
                    PtRole role = ptRoleMapper.selectById(us.getRoleId());
                    if (!role.getShowPhase()) {
                        space.setPhaseId(0);
                    } else {
                        space.setPhaseId(us.getPhaseId());
                    }
                    if (!role.getShowGrade()) {
                        space.setGradeId(0);
                    } else {
                        space.setGradeId(us.getGradeId());
                    }
                    if (!role.getShowSubject()) {
                        space.setSubjectId(0);
                    } else {
                        space.setSubjectId(us.getSubjectId());
                    }
                }
                ptUserRoleMapper.updateById(space);
                accountService.sendUserRoleMessege(MessageTypes.USER_ROLE_UPDATE.name(), space);
            }
        }
        result.setMsg("操作成功");
        return result;
    }

    @Override
    public List<PtUserRole> findHeadmaster(PtUserRole userRole) {
        PtRole role=new PtRole();
        role.setRoleCode("banzhuren");
        PtRole role1=ptRoleMapper.selectOne(role);
        if (role1!=null){
            EntityWrapper<PtUserRole> param=new EntityWrapper<>();
            if(null!=userRole.getGradeId()){
                param.eq("grade_id",userRole.getGradeId());
            }
            param.eq("role_id",role1.getId());
            param.eq("enable",1);
            param.eq("org_id",userRole.getOrgId());
            if (userRole.getSubjectId()!=null){
                param.eq("subject_id",0);
            }
            if (userRole.getPhaseId()!=null){
                param.eq("phase_id",0);
            }
            if (StringUtils.isNotBlank(userRole.getName())) {
                param.like("name",userRole.getName());
            }
            return selectList(param);
        }

        return null;
    }

    @Override
    public List<PtUserRole> listTeacherByOrg_Phase_Subject(PtUserRole userRole) {
        EntityWrapper <PtUserRole> ur = new EntityWrapper<>();
        ur.setSqlSelect(" distinct account_id,name");
        ur.eq("org_id",userRole.getOrgId());
        ur.eq("subject_id",userRole.getSubjectId());
        ur.eq("phase_id",userRole.getPhaseId());
        if(null!=userRole.getGradeId()){
            ur.eq("grade_id",userRole.getGradeId());
        }
        if (StringUtils.isNotBlank(userRole.getName())) {
            ur.like("name",  userRole.getName());
        }
        ur.eq("enable",1);
        ur.eq("sys_role_id",SysRole.TEACHER.getId());
        return selectList(ur);
    }
}
